#include <Arduino.h>
#include "LightClient.h"

// wifi ssid与密码
char *ssid = "test0";
char *passphrase = "12345687";
// 服务端 地址与端口
char *host = "192.168.137.1";
uint16_t serverPost = 8081;
// 设备 用户名密码
char *userName = "light";
char *passwd = "light";

LightClient lightClient;
MsgHeader msgHeader;

void setup() {
    Serial.begin(115200);
    while (!Serial) {
    }
    ConnectInfo connectInfo;
    connectInfo.ssid = ssid;
    connectInfo.passphrase = passphrase;
    connectInfo.host = host;
    connectInfo.serverPost = serverPost;
    connectInfo.userName = userName;
    connectInfo.passwd = passwd;
    connectInfo.attrCount = 2;
    connectInfo.devAttr = "version:1.0\ndevType:led\n";

    lightClient.connectServer(&connectInfo);
    pinMode(LED_BUILTIN, OUTPUT);

}

void loop() {
    int result = lightClient.readMsgHeader(&msgHeader);

    if (result == MSG_FAILED) {
        return;
    }
    int opCode = msgHeader.opCode;
    Serial.printf("cmdId:%d,opCode:%d\n", msgHeader.cmdIdVal, opCode);
    int val = lightClient.readInt('\n');
    // 释放以下注释 则选择 数字输出，当前保留模拟输出模拟输出
    //#define DIGITAL

#ifdef DIGITAL
    digitalWrite(LED_BUILTIN, val ? HIGH : LOW);
#else
    // 红石信号 0~15 映射到 0 到模拟输出的最大值
#ifdef ESP8266
#define MAX_VAL  1023
#elif defined ESP32
#define MAX_VAL  255
#endif

    analogWrite(LED_BUILTIN, MAX_VAL * val / 15);
#endif

}